import { ChangeEvent } from "react";

interface NotesViewProps {
  notes: Note[];
  activeNote: Note | undefined;
  onNoteSelect: (noteId: string) => void;
  onNoteAdd: () => void;
  onNoteEdit: (title: string, body: string) => void;
  onNoteDelete: (noteId: string) => void;
}

export default function NotesView({
  notes,
  activeNote,
  onNoteSelect,
  onNoteAdd,
  onNoteEdit,
  onNoteDelete,
}: NotesViewProps) {
  const handleNoteItemClick = (noteId: string) => {
    onNoteSelect(noteId);
  };

  const handleNoteItemDelete = (noteId: string) => {
    // const doDelete = window.confirm("确认要删除该笔记吗?");
    // if (doDelete) {
    //   onNoteDelete(noteId);
    // }
    onNoteDelete(noteId);
  };

  const handleNoteTitleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const updatedTitle = event.target.value.trim();
    onNoteEdit(updatedTitle, activeNote!.body);
  };

  const handleNoteBodyChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
    const updatedBody = event.target.value.trim();
    onNoteEdit(activeNote!.title, updatedBody);
  };

  return (
    <div className="notes__wrapper">
      <div className="notes__sidebar">
        <button className="notes__add" type="button" onClick={onNoteAdd}>
          添加新的笔记 📒
        </button>
        <div className="notes__list">
          {notes.map((note) => (
            <div
              className={`notes__list-item ${
                note.id === activeNote?.id ? "notes__list-item--selected" : ""
              }`}
              key={note.id}
              onClick={() => handleNoteItemClick(note.id)}
              onDoubleClick={() => handleNoteItemDelete(note.id)}
            >
              <div className="notes__small-title">{note.title}</div>
              <div className="notes__small-body">
                {note.body.substring(0, 60)}
                {/* {note.body.length > 60 ? "..." : ""} */}
              </div>
              <div className="notes__small-updated">
                {new Date(note.updated).toLocaleString(undefined, {
                  dateStyle: "full",
                  timeStyle: "short",
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className={`notes__preview ${activeNote ? "show" : ""}`}>
        <input
          className="notes__title"
          type="text"
          placeholder="新笔记..."
          value={activeNote?.title || ""}
          onChange={handleNoteTitleChange}
          // onBlur={handleNoteTitleChange}
        />
        <textarea
          className="notes__body"
          value={activeNote?.body || ""}
          onChange={handleNoteBodyChange}
          // onBlur={handleNoteBodyChange}
        ></textarea>
      </div>
    </div>
  );
}
